import fs from 'fs/promises';
import fetch from 'node-fetch';
import https from 'https';
import common from '../../lib/common/common.js'

const FILE_PATH = './data/CS2InventoryQuery.json';
const STEAM_API_URL = 'https://steamcommunity.com/inventory/';

export class CS2InventoryQuery extends plugin {
    constructor() {
        super({
            name: 'CS2InventoryQuery',
            dsc: 'CS2 Inventory Query',
            event: 'message',
            priority: 10,
            rule: [
                { reg: /^cs库存查询$/i, fnc: 'invQuery' },
                { reg: /^绑定steamid\d+$/i, fnc: 'bindSteamId' }
            ]
        });
        this.initDataFile();
    }

    async initDataFile() {
        try {
            await fs.access(FILE_PATH);
        } catch {
            await fs.writeFile(FILE_PATH, JSON.stringify({}));
        }
    }

    async readDataFile() {
        const data = await fs.readFile(FILE_PATH, 'utf8');
        return JSON.parse(data);
    }

    async writeDataFile(data) {
        await fs.writeFile(FILE_PATH, JSON.stringify(data));
    }

    async invQuery(e) {
        const fileData = await this.readDataFile();
        const steamId = fileData[e.user_id];
        if (!steamId) {
            return e.reply('请先绑定SteamID\r\n指令: 绑定steamid <steamid>\r\nSteamID是Steam打开个人主页左上角链接中的数字');
        }

        await e.reply('正在查询库存...\r请稍等...');
        try {
            const inventoryData = await this.fetchInventory(steamId);
            if (!inventoryData) {
                return e.reply('无法获取库存信息，请确认您的SteamID是否正确或库存是否为公开状态。');
            }
            const inventoryCount = inventoryData.descriptions.length;
            const msg = `您的CS2库存(${inventoryCount}件)`;
            const msgItems = [];
            for (const item of inventoryData.descriptions) {
                const msgItem = []
                msgItem.push(`${item.market_name}\r`);
                msgItem.push(segment.image('https://community.cloudflare.steamstatic.com/economy/image/' + item.icon_url));
                msgItems.push(msgItem)
            }
            const forwardMsg = await common.makeForwardMsg(e, msgItems, msg);
            e.reply(forwardMsg);
        } catch (error) {
            console.error('获取库存时出错:', error);
            e.reply('获取库存信息失败，请稍后再试。');
        }
    }

    async fetchInventory(steamId) {
        const agent = new https.Agent({ rejectUnauthorized: false });
        const response = await fetch(`${STEAM_API_URL}${steamId}/730/2?l=schinese`, {
            agent,
            timeout: 10000
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.text();
        if (data === 'null') {
            return null; // 接口返回 'null' 字符串
        }
        try {
            const jsonData = JSON.parse(data);
            return jsonData && jsonData.descriptions ? jsonData : null;
        } catch (error) {
            console.error('解析库存数据时出错:', error);
            return null;
        }
    }

    async bindSteamId(e) {
        const steamId = e.msg.replace(/绑定steamid/i, '').trim();
        if (!/^\d+$/.test(steamId)) {
            return e.reply('请输入有效的SteamID\r\nSteamID是Steam打开个人主页左上角链接中的数字');
        }

        const fileData = await this.readDataFile();
        fileData[e.user_id] = steamId;
        await this.writeDataFile(fileData);
        e.reply(`已绑定SteamID: ${steamId}\r\n如需更改，请重新使用绑定指令`);
    }
}